<?php

namespace app\admin\service;

use app\common\model\article\Article;
use app\common\model\user\User;
use tmcore\base\BaseService;

/**
 * 工作台服务类
 */
class WorkbenchService extends BaseService
{

    /**
     * 获取首页数据
     * @return array
     */
    public static function getHomeData()
    {
        $data = [
            'article_number' => Article::count(),
            'article_hits' => Article::sum('actual_hits') + Article::sum('init_hits'),
            'user_number' => User::count(),
            'user_today' => User::where([['create_time', '>', strtotime(date('Y-m-d 00:00:00'))], ['create_time', '<', strtotime(date('Y-m-d 23:59:59'))]])->count(),
        ];

        $list = Article::where(['status' => 1])->order('actual_hits', 'desc')->limit(4)->append(['hits','cate_name'])->field('id,title,image,init_hits,actual_hits,cate_id')->select()->toArray();
        foreach ($list as &$value) {
            $value['image'] = get_file_url($value['image']);
        }
        $data['article_rank_list'] = $list;
        $data['user_chart'] = self::getHomeChart(['day' => 1])['user_chart_data'];

        return $data;
    }


    /**
     * 首页图标数据
     * @param $params
     * @return array[]
     */
    public static function getHomeChart($params)
    {
        // 数据
        $day = $params['day'] ?? 1;
        $days = []; // 时间点

        if ($day>1) {
            // 循环天数
            for ($i=0;$i<$day;$i++) {
                $days[] = date("Y-m-d", strtotime('-'. $i . 'day'));
            }
        } else {
            //今日
            if ($day == 1) {
                $dayNow = date("Y-m-d", strtotime('-'. '0' . 'day'));
                for ($i=0; $i < 24; $i++) {
                    $days[] = $dayNow.' '.$i.':00';
                }
            }
            //昨日
            if ($day == -1) {
                $dayNow = date("Y-m-d", strtotime('-'. '1' . 'day'));
                for ($i=0; $i < 24; $i++) {
                    $days[] = $dayNow.' '.$i.':00';
                }
            }
        }

        if ($day>1) {
            $days = array_reverse($days);//倒序
        }

        return [
            'user_chart_data' => [
                'days'=>$days,
                'data'=>self::getUserData($day, $days)
            ]
        ];
    }

    private static function getUserData($day, $days) {
        $data = [];
        // 用户数据
        foreach ($days as $key=>$value) {
            $start = strtotime($value);

            if ($day>1) {
                $end = $start+24*60*60;
            } else {
                $end = $start+60*60;
            }

            $where = [];
            $where[] = ['create_time','>=',$start];
            $where[] = ['create_time','<=',$end];

            $data[] = User::where($where)->count();
        }
        return $data;
    }

}